/**
 * @author salman.humdullah
 */
exports.GAStoreLoader = Core.Class.subclass({
	classname: 'GAStoreLoader',

	initialize : function(responseObject) {
		this._delegate = null;
		this._responseObject = responseObject;
		this._storeListener = null;
		this._baseURL = null;
		this._gameName = null;
		this._parseStores = true;
		this._successfullyDownloadedStore = 0;
		this._totalStoresToDownload = 0;
		//this._updatedVersionStores = [];
		this._storage = new Storage.KeyValue();
		var startingServer = Core.Capabilities.getStartingServer();
		if (startingServer!= null && startingServer.length > 30) {
			startingServer = startingServer.substring(0, 30);
		}
		this._keyPrefix = "_" + startingServer + GAConfigurations.getGameCode();
	},

	loadStores : function(delegate)
	{
		this._delegate = delegate;
		this._baseURL = this._responseObject.getStoreServer();
		this._gameName = GAConfigurations.getGameName();
		var storeVersionModel = this._responseObject.getStoresModel();
		this._totalStoresToDownload = storeVersionModel.length;
		if (this._totalStoresToDownload == 0) {
			this._parseStores = false;
			this._delegate.storeDownloaderSuccess(this._parseStores);
		}
		else{
			this._updatedStoreVersions();
		}
	},
	_updatedStoreVersions : function(){
		//var storeNames = this._responseObject.getStoreNames();
		var stores = this._responseObject.getStoresModel();
		var length = stores.length;
		for( var i=length-1 ; i >= 0; i--)
		{
			///zaki local
			this._getVersionKey();	
//			this._storage.getItem(stores[i].getVisibleId() + this._keyPrefix, this._getVersionKey.bind(this));

		}
	},
	_getVersionKey : function(error, currentVersion, visibleId){
		
		///zaki local
		this._successfullyDownloadedStore++;
		if(this._successfullyDownloadedStore == this._totalStoresToDownload) {
			this._delegate.storeDownloaderSuccess(this._parseStores);
		}
		
		return;
	
		
		
		var parts = visibleId.split("_");
		
		if (parts.length > 1) {
			visibleId = parts[0];
		}
		//console.log("zaki:::: current version is "+currentVersion+ "    parts id are "+parts+ "    visibleId are "+visibleId);

		var storeVersion = this._responseObject.getStoreVersion(visibleId);
		if(currentVersion == 0 || currentVersion == null || typeof(currentVersion) == 'undefined' || currentVersion == ''){
			this._saveToPreferenceAndDownload(visibleId);
		}
		else if(storeVersion > currentVersion){
			this._saveToPreferenceAndDownload(visibleId);
		}
		else{
			this.isStoreExist(visibleId);
			this._successfullyDownloadedStore++;
			if(this._successfullyDownloadedStore == this._totalStoresToDownload) {
				this._delegate.storeDownloaderSuccess(this._parseStores);
			/*}else{
				this._updatedStoreVersions();*/
			}
		}
	},
	
	_dbFileReadCallback: function (error,contents){
//        console.log('>> dbFileReadCallback 111 '+error);
       if(!error){
       }else{
           try{
           var parts = error.split("/");
           var id = parts[parts.length-1].split(".");
           this._saveToPreferenceAndDownload(id[0]);
           }catch(Exception){
               
           }
           
       }
   
   },

	isStoreExist: function (visibleID){
       Storage.FileSystem.readFile("./Content/stores/"+visibleID+".json",this._dbFileReadCallback.bind(this));
   
   },
	
	
	_saveToPreferenceAndDownload : function(visibleId){
		//this._updatedVersionStores.push(visibleId);
		this._startDownloadingStores(visibleId);
	},
	_startDownloadingStores : function(visibleId){
		var storeId = this._responseObject.getStoreId(visibleId);
		var url = this._baseURL+"serverstore?store_id=" +storeId+"&game="+this._gameName+"&type=json";
		url=encodeURI(url);
		console.log("Downloading store: " + url);
		var fileDownloader = new GAFileDownloader('./Content/'+visibleId+'.zip' ,'GET' ,url ,null ,new this.GAStoreDownloaderDelegate(visibleId, this));
		fileDownloader.startDownloading();
	},


	$GAStoreDownloaderDelegate : Core.Class.subclass({
		classname : 'GAStoreWebFetcherDelegate',

		initialize : function(storeVisibleId, parent){
			this._parent = parent;
			this._storeVisibleId = storeVisibleId;
		},
		/* abid . hussain*/
		onDownloadSuccess : function(fileDownloader ,fileSignature){
			try{
				var destination = './Content/stores/';
				Storage.FileSystem.decompressFile('./Content/'+this._storeVisibleId+'.zip', destination,true,this._zipExtractionCb.bind(this));
				if( fileDownloader != null){
					fileDownloader.destroy();
					fileDownloader = null;
				}
			}
			catch(exception){
				this._parent._delegate.storeDownloaderFailure(exception);
			}
		},
		/* abid . hussain*/
		_zipExtractionCb : function(error, files){
			if(!error) {
				var storeVersion = this._parent._responseObject.getStoreVersion(this._storeVisibleId);
				this._parent._successfullyDownloadedStore++;
				Storage.FileSystem.deleteFile('./Content/'+this._storeVisibleId+'.zip');
				this._parent._storage.setItem(this._storeVisibleId + this._parent._keyPrefix, storeVersion, this._storeVersionCommittedCB.bind(this));
				//Storage.FileSystem.readFile("./Content/stores/" + this._storeVisibleId + ".json", this.readCompleted.bind(this));
				if(this._parent._successfullyDownloadedStore == this._parent._totalStoresToDownload){
					this._parent._delegate.storeDownloaderSuccess(this._parent._parseStores);
				}
			}
			else{
				this._parent._delegate.storeDownloaderFailure("Zip extraction failed for store with visible Id " + this._storeVisibleId);
			}
		},

		_storeVersionCommittedCB : function(error, key){
		},

		/* abid . hussain*/
		onDownloadFailure : function(fileDownloader, statusCode){
			console.log('Download failed for Store visible Id-> '+this._storeVisibleId+' with StatusCode = '+ statusCode);
			this._parent._delegate.storeDownloaderFailure(statusCode);
			if(fileDownloader != null){
				fileDownloader.destroy();
				fileDownloader = null;
			}
		},
		destroy : function(){
			this._parent = null;
			this._storeVisibleId = null;
		}

	}),

	destroy : function() {
		this._delegate = null;
		/*var size = this._updatedVersionStores.length;
		for(var i=0; i<size; i++){
			this._updatedVersionStores[i] = null;
		}
		this._updatedVersionStores = null;*/
		this._responseObject = null;
		this._storage = null;
		this._keyPrefix = null;
	}

});
